/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-12     GC       the first version
 */

#include "uart.h"
#include "string.h"

#define SAMPLE_UART_NAME       "uart1"

char lock_on[] = "\r\nPOST /devices/864738962/datapoints HTTP/1.1\r\napi-key:ZNkJb01crQ=uNJ9Pclqs2aKFJhs=\r\nHost:api.heclouds.com\r\nContent-Length:61\r\n\r\n{\"datastreams\":[{\"id\":\"switch\",\"datapoints\":[{\"value\":1}]}]}";
char lock_off[] = "\r\nPOST /devices/864738962/datapoints HTTP/1.1\r\napi-key:ZNkJb01crQ=uNJ9Pclqs2aKFJhs=\r\nHost:api.heclouds.com\r\nContent-Length:61\r\n\r\n{\"datastreams\":[{\"id\":\"switch\",\"datapoints\":[{\"value\":0}]}]}";



/* 用于接收消息的信号量 */
struct rt_semaphore rx_sem;



rt_thread_t rx_thread;

rt_device_t serial;

rt_uint8_t At_Cmd_Num = 1;
rt_uint8_t rx_num = 1;
rt_uint8_t uart_rec_data[512];
rt_uint8_t rec_data_len;

/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

int uart_sendstring(char *str) {
    rt_device_write(serial, 0, str, (strlen(str)));
}

static void serial_rx_entry(void *parameter)
{
    char ch;

    while (1)
    {
        //中断函数接收数据部分
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
        rt_thread_mdelay(100);
    }
}

/*
函数功能：uart线程
函数形参：void
函数返回值：void
函数说明：线程优先级为  5  时间片为10
*/
int uart_init(void)
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
    rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);
    /* 查找系统中的串口设备 ，查找串口1*/
    serial = rt_device_find(uart_name);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n", uart_name);
        return RT_ERROR;
    }
    //创建事件
 //   event1 = rt_event_create("set1", RT_IPC_FLAG_FIFO);
    /* if(!event1)
    {
        return RT_ERROR;
    }
    初始化信号量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(serial, uart_input);
    /* 发送字符串 */
   //rt_device_write(serial, 0, lock_on, (sizeof(lock_on) - 1));

    /* 创建 serial 线程 */
    rx_thread = rt_thread_create("serial", serial_rx_entry, RT_NULL, 512, 4, 10);
    /* 创建成功则启动线程 */
    if (rx_thread != RT_NULL)
    {
        rt_kprintf("uart1 rx success.\n");
        rt_thread_startup(rx_thread);
    }
    else
    {
        ret = RT_ERROR;
    }
    return ret;
}
INIT_APP_EXPORT(uart_init);



